package com.ruoyi.cqjd.common;

import com.ruoyi.common.core.domain.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author kaza
 * @create 2022-04-27 21:03
 **/
@ControllerAdvice(annotations = {RestController.class, Controller.class})//给有RestController注解，Controller注解的类加捕获异常的方法
@ResponseBody
@Slf4j
public class MyGlobalExceptionHandler {

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)//给这个异常加处理
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException e){
        log.info(e.getMessage());

        if (e.getMessage().contains("Duplicate entry")){
            String[] split = e.getMessage().split(" ");
            String msg = split[2] + "已存在";
            return R.fail(msg);
        }

        return R.fail("未知错误");
    }

    @ExceptionHandler(CustomException.class)//给这个异常加处理
    public R<String> exceptionHandler(CustomException e){
        log.info(e.getMessage());

        return R.fail(e.getMessage());
    }

}
